from numpy import arange, cos, linspace, pi, sin, random
from scipy.interpolate import splprep, splev
import ConfigParser, os
import sys, math

if len(sys.argv) != 2:
  sys.exit("Please specify a file name as input argument!")

try:
  input_file = sys.argv[1]
  fp=open (input_file, "r")
except:
  sys.exit("Input file not found!")
  
# read parameters from config file
config = ConfigParser.ConfigParser()
config.readfp(fp)
section_names = config.sections()
k = config.getint('Spline', "order")
s = config.getfloat('Spline', "smoothness")
iso = config.getint('Film', 'iso')
film_type = config.get('Film', 'type')
development = config.get('Film', 'development')
values = config.get('Data', 'points')
points = eval(values)
standard = config.get('Standard', 'preset')
z=[]
x=[]
for p in points:
  z.append(p[0])
  x.append(p[1])
text = film_type + ", " + development
text_iso = "ISO (test): " + str(iso)

# spline parameters
nest=-1 # estimate of number of knots needed (-1 = maximal)

# find the knot points
tckp,u = splprep([x,z],s=s,k=k,nest=-1)

# evaluate spline, including interpolated points
xnew,znew = splev(linspace(0,1,400),tckp)

# parameters
if standard == 'AA':
  sp_density = 0.10
  sp_zone = 1.0 # zone I
  upper_zone = 8.0
elif standard == 'LW':
  sp_density = 0.17
  sp_zone = 1.5 # zone I.5
  upper_zone = 8.5
elif standard == 'ISO':
  sp_density = 0.10
  sp_zone = 1.0 # zone I
  upper_zone = 1.0 + 1.3/0.3
else:
  sys.exit("Unknown preset!")

# evaluate speed point
i = 0
for d in xnew:
  if d >= sp_density:
    break  
  i += 1
m = (xnew[i]-xnew[i-1])/(znew[i]-znew[i-1])
new_sp_zone = (sp_density + m*znew[i-1]-xnew[i-1])/m
new_iso = iso * 2.**((sp_zone-new_sp_zone))

# evaluate density in zone VIII.5
new_upper_zone = upper_zone - sp_zone + new_sp_zone

i = 0
for e in znew:
  if e >= new_upper_zone:
    break  
  i += 1

m = (xnew[i]-xnew[i-1])/(znew[i]-znew[i-1])
d = m*new_upper_zone - m*znew[i-1]+xnew[i]
gamma = (d-sp_density)/((upper_zone-sp_zone)*0.3)

# graphics
import pylab
#pylab.subplot(2,2,2)
data,=pylab.plot(z,x,'bo-',label='data')
fit,=pylab.plot(znew,xnew,'r-',label='fit')
#pylab.legend()
pylab.text(1.5,1.4,"TEST DATA:",fontsize=10)
pylab.text(1.5,1.3,text,fontsize=10)
pylab.text(1.5,1.2,text_iso,fontsize=10)
pylab.text(1.5,1.1,"spline order = "+str(k), fontsize=10)
pylab.text(1.5,1.0,"smoothness = "+str(s),fontsize=10)
pylab.text(1.5,0.9,"preset: " + standard, fontsize=10)
pylab.text(5,0.4,"TEST RESULTS:",fontsize=10)
pylab.text(5,0.3,"effective ISO = "+str(new_iso),fontsize=10)
pylab.text(5,0.2,"average gradient = "+str(gamma),fontsize=10)
pylab.ylabel('transmission density (log units)')
pylab.xlabel('exposure (zone)')
pylab.xticks(arange(12), ('0', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII'))
pylab.axvline(x=new_sp_zone, color='g',alpha=0.2)
pylab.axvline(x=new_upper_zone, color='g', alpha=0.2)

output_file = os.path.splitext(input_file)[0]
pylab.savefig(output_file)

